<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票财务分析报告系统</title>
    <!-- 引入Bootstrap -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">
    <!-- 引入ECharts -->
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.2/echarts.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .header h1 {
            margin: 0;
            font-weight: 600;
        }
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        .card-header {
            background-color: #667eea;
            color: white;
            border-radius: 10px 10px 0 0 !important;
            font-weight: 500;
        }
        .btn-primary {
            background-color: #667eea;
            border-color: #667eea;
        }
        .btn-primary:hover {
            background-color: #5a67d8;
            border-color: #5a67d8;
        }
        .btn-info {
            background-color: #38b2ac;
            border-color: #38b2ac;
        }
        .btn-info:hover {
            background-color: #319795;
            border-color: #319795;
        }
        .badge-success {
            background-color: #38b2ac;
        }
        .badge-warning {
            background-color: #ed8936;
        }
        .table-hover tbody tr:hover {
            background-color: #f8f9fa;
        }
        .stats-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 10px;
            padding: 1.5rem;
            text-align: center;
            margin-bottom: 1rem;
        }
        .stats-value {
            font-size: 2rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 0.5rem;
        }
        .stats-label {
            color: #4a5568;
            font-size: 0.9rem;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .chart-container {
            height: 300px;
            margin-top: 1rem;
        }
    </style>
</head>
<body>
    <!-- 加载遮罩层 -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="text-center">
            <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;" role="status">
                <span class="sr-only">加载中...</span>
            </div>
            <p class="mt-3">数据处理中，请稍候...</p>
        </div>
    </div>

    <!-- 头部 -->
    <header class="header">
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <h1><i class="fas fa-chart-line mr-2"></i>股票财务分析报告系统</h1>
                    <p class="mt-1">实时监控A股市场关键财务指标，助力投资决策</p>
                </div>
                <div class="col-md-4 text-right">
                    <button id="fetchDataBtn" class="btn btn-light btn-lg mt-2">
                        <i class="fas fa-sync-alt mr-2"></i>抓取最新数据
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 主要内容 -->
    <div class="container">
        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-value" id="totalStocks">0</div>
                    <div class="stats-label">总股票数</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-value" id="avgPE">0.00</div>
                    <div class="stats-label">平均市盈率(TTM)</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-value" id="avgPB">0.00</div>
                    <div class="stats-label">平均市净率</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <div class="stats-value" id="avgROE">0.00</div>
                    <div class="stats-label">平均ROE(%)</div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-pie mr-2"></i>市盈率分布
                    </div>
                    <div class="card-body">
                        <div id="peDistributionChart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <i class="fas fa-chart-bar mr-2"></i>ROE Top 10
                    </div>
                    <div class="card-body">
                        <div id="roeTop10Chart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 股票列表 -->
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-6">
                        <i class="fas fa-list-alt mr-2"></i>股票财务分析报告列表
                    </div>
                    <div class="col-md-6 text-right">
                        <div class="input-group input-group-sm" style="width: 300px; display: inline-block;">
                            <input type="text" id="searchInput" class="form-control" placeholder="搜索股票代码或名称">
                            <div class="input-group-append">
                                <button id="searchBtn" class="btn btn-outline-secondary" type="button">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>股票代码</th>
                                <th>股票名称</th>
                                <th>最新交易日期</th>
                                <th>报告期</th>
                                <th>市盈率(TTM)</th>
                                <th>市净率</th>
                                <th>ROE(%)</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="stockReportTable">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer text-right">
                <button id="processAllBtn" class="btn btn-info">
                    <i class="fas fa-cogs mr-2"></i>处理所有股票近20个季度数据
                </button>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="mt-5 py-4 bg-light">
        <div class="container text-center text-muted">
            <p>© 2024 股票财务分析报告系统 - 数据来源于东方财富网</p>
            <p class="small">更新时间: <span id="updateTime"></span></p>
        </div>
    </footer>

    <!-- 消息提示框 -->
    <div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position: fixed; top: 20px; right: 20px; min-width: 300px; z-index: 1050;">
        <div class="toast-header">
            <strong class="mr-auto" id="toastTitle">提示</strong>
            <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="toast-body" id="toastMessage"></div>
    </div>

    <!-- 引入jQuery和Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>

    <script>
        $(document).ready(function() {
            // 设置更新时间
            $('#updateTime').text(new Date().toLocaleString());
            
            // 加载股票报告数据
            loadStockReports();
            
            // 抓取数据按钮点击事件
            $('#fetchDataBtn').click(function() {
                showLoading();
                $.ajax({
                    url: '/stockpereport/fetch',
                    type: 'GET',
                    success: function(data) {
                        hideLoading();
                        if (data.success) {
                            showToast('成功', data.message, 'success');
                            // 重新加载数据
                            loadStockReports();
                        } else {
                            showToast('失败', data.message, 'danger');
                        }
                    },
                    error: function() {
                        hideLoading();
                        showToast('错误', '网络请求失败，请稍后重试', 'danger');
                    }
                });
            });
            
            // 处理所有股票近20个季度数据按钮点击事件
            $('#processAllBtn').click(function() {
                if (confirm('确定要处理所有股票近20个季度数据吗？此操作可能需要较长时间。')) {
                    showLoading();
                    // 这里简化处理，实际应该循环处理每个股票
                    $.ajax({
                        url: '/stockpereport/fetch',
                        type: 'GET',
                        success: function(data) {
                            hideLoading();
                            if (data.success) {
                                showToast('成功', '季度数据处理完成', 'success');
                                loadStockReports();
                            } else {
                                showToast('失败', data.message, 'danger');
                            }
                        },
                        error: function() {
                            hideLoading();
                            showToast('错误', '网络请求失败，请稍后重试', 'danger');
                        }
                    });
                }
            });
            
            // 搜索按钮点击事件
            $('#searchBtn').click(function() {
                filterStockReports();
            });
            
            // 回车键搜索
            $('#searchInput').keypress(function(e) {
                if (e.which === 13) {
                    filterStockReports();
                }
            });
        });
        
        // 加载股票报告数据
        function loadStockReports() {
            $.ajax({
                url: '/stockpereport/api/reports',
                type: 'GET',
                success: function(data) {
                    if (data.code === 200) {
                        renderStockReportTable(data.data);
                        updateStatistics(data.data);
                        renderCharts(data.data);
                    }
                }
            });
        }
        
        // 渲染股票报告表格
        function renderStockReportTable(reports) {
            let tbody = $('#stockReportTable');
            tbody.empty();
            
            if (reports.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="9" class="text-center text-muted">暂无数据</td>
                    </tr>
                `);
                return;
            }
            
            reports.forEach((report, index) => {
                tbody.append(`
                    <tr>
                        <td>${index + 1}</td>
                        <td>${report.securityCode}</td>
                        <td>${report.securityName}</td>
                        <td>${formatDate(report.tradeDate)}</td>
                        <td>${formatDate(report.reportDate)}</td>
                        <td class="${getPEClass(report.peTTM)}">${formatNumber(report.peTTM)}</td>
                        <td>${formatNumber(report.pbRatio)}</td>
                        <td class="${getROEClass(report.roe)}">${formatNumber(report.roe)}</td>
                        <td>
                            <a href="/stockpereport/detail/${report.securityCode}" class="btn btn-sm btn-primary">
                                <i class="fas fa-eye mr-1"></i>查看详情
                            </a>
                            <button onclick="processQuarterlyData('${report.securityCode}', '${report.securityName}')" class="btn btn-sm btn-info ml-1">
                                <i class="fas fa-calendar-alt mr-1"></i>处理季度数据
                            </button>
                        </td>
                    </tr>
                `);
            });
        }
        
        // 更新统计数据
        function updateStatistics(reports) {
            if (reports.length === 0) return;
            
            let totalStocks = reports.length;
            let sumPE = 0, sumPB = 0, sumROE = 0;
            let validPECount = 0, validPBCount = 0, validROECount = 0;
            
            reports.forEach(report => {
                if (report.peTTM) { sumPE += report.peTTM; validPECount++; }
                if (report.pbRatio) { sumPB += report.pbRatio; validPBCount++; }
                if (report.roe) { sumROE += report.roe; validROECount++; }
            });
            
            $('#totalStocks').text(totalStocks);
            $('#avgPE').text((sumPE / validPECount).toFixed(2));
            $('#avgPB').text((sumPB / validPBCount).toFixed(2));
            $('#avgROE').text((sumROE / validROECount).toFixed(2));
        }
        
        // 渲染图表
        function renderCharts(reports) {
            renderPeDistributionChart(reports);
            renderRoeTop10Chart(reports);
        }
        
        // 渲染市盈率分布图
        function renderPeDistributionChart(reports) {
            let peBelow10 = 0, pe10_20 = 0, pe20_30 = 0, pe30_50 = 0, peAbove50 = 0;
            
            reports.forEach(report => {
                if (report.peTTM) {
                    if (report.peTTM < 10) peBelow10++;
                    else if (report.peTTM < 20) pe10_20++;
                    else if (report.peTTM < 30) pe20_30++;
                    else if (report.peTTM < 50) pe30_50++;
                    else peAbove50++;
                }
            });
            
            let chart = echarts.init(document.getElementById('peDistributionChart'));
            let option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        name: '市盈率分布',
                        type: 'pie',
                        radius: '50%',
                        data: [
                            {value: peBelow10, name: 'PE < 10'},
                            {value: pe10_20, name: '10 ≤ PE < 20'},
                            {value: pe20_30, name: '20 ≤ PE < 30'},
                            {value: pe30_50, name: '30 ≤ PE < 50'},
                            {value: peAbove50, name: 'PE ≥ 50'}
                        ],
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            };
            chart.setOption(option);
        }
        
        // 渲染ROE Top 10图表
        function renderRoeTop10Chart(reports) {
            let sortedReports = [...reports].filter(r => r.roe).sort((a, b) => b.roe - a.roe).slice(0, 10);
            
            let chart = echarts.init(document.getElementById('roeTop10Chart'));
            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: sortedReports.map(r => r.securityName)
                },
                series: [
                    {
                        name: 'ROE(%)',
                        type: 'bar',
                        data: sortedReports.map(r => r.roe.toFixed(2)),
                        itemStyle: {
                            color: '#667eea'
                        }
                    }
                ]
            };
            chart.setOption(option);
        }
        
        // 处理季度数据
        function processQuarterlyData(securityCode, securityName) {
            showLoading();
            $.ajax({
                url: `/stockpereport/process20Quarters?securityCode=${securityCode}&securityName=${encodeURIComponent(securityName)}`,
                type: 'GET',
                success: function(data) {
                    hideLoading();
                    if (data.success) {
                        showToast('成功', data.message, 'success');
                    } else {
                        showToast('失败', data.message, 'danger');
                    }
                },
                error: function() {
                    hideLoading();
                    showToast('错误', '网络请求失败，请稍后重试', 'danger');
                }
            });
        }
        
        // 过滤股票报告
        function filterStockReports() {
            let searchTerm = $('#searchInput').val().toLowerCase();
            let rows = $('#stockReportTable tr');
            
            rows.each(function() {
                let securityCode = $(this).find('td:nth-child(2)').text().toLowerCase();
                let securityName = $(this).find('td:nth-child(3)').text().toLowerCase();
                
                if (securityCode.includes(searchTerm) || securityName.includes(searchTerm)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
        
        // 显示加载遮罩
        function showLoading() {
            $('#loadingOverlay').show();
        }
        
        // 隐藏加载遮罩
        function hideLoading() {
            $('#loadingOverlay').hide();
        }
        
        // 显示提示消息
        function showToast(title, message, type) {
            $('#toastTitle').text(title);
            $('#toastMessage').text(message);
            
            let toast = $('#toast');
            toast.removeClass('bg-success bg-danger bg-info bg-warning');
            toast.addClass(`bg-${type}`);
            toast.addClass('text-white');
            
            toast.toast('show');
        }
        
        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            let date = new Date(dateString);
            return date.toLocaleDateString('zh-CN');
        }
        
        // 格式化数字
        function formatNumber(num) {
            if (num === null || num === undefined) return '-';
            return num.toFixed(2);
        }
        
        // 获取市盈率样式类
        function getPEClass(pe) {
            if (!pe) return '';
            if (pe < 15) return 'text-success';
            if (pe < 30) return 'text-warning';
            return 'text-danger';
        }
        
        // 获取ROE样式类
        function getROEClass(roe) {
            if (!roe) return '';
            if (roe > 15) return 'text-success';
            if (roe > 8) return 'text-warning';
            return 'text-danger';
        }
        
        // 窗口大小改变时重新渲染图表
        $(window).resize(function() {
            echarts.getInstanceByDom(document.getElementById('peDistributionChart'))?.resize();
            echarts.getInstanceByDom(document.getElementById('roeTop10Chart'))?.resize();
        });
    </script>
</body>
</html>